package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.JwtConstants;
import com.zzyl.dto.*;
import com.zzyl.entity.Member;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.MemeberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.CustomerUserLoginService;
import com.zzyl.service.WxService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.MemeberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;



@Slf4j
@Service
public class CustomerUserLoginServiceImpl implements CustomerUserLoginService {

    @Autowired
    private WxService wxService;
    @Autowired
    private MemeberMapper memeberMapper;


    private JwtConstants jwtConstants;
    @Autowired
    private  JwtProperties jwtProperties;
    @Override
    public MemeberVo login(MemberLoginDTO dto) {
        // code2session获取用户的openid
        Code2sessionResultDto code2sessionResultDto = wxService.code2session(dto.getCode());
        if(code2sessionResultDto.getErrcode() != null){
            throw new BaseException( BasicEnum.WX_LOGIN_ERROR);
        }
        String openid = code2sessionResultDto.getOpenid();
        log.info("openid:{}", openid);
        // 根据openid查询数据库 判断是否是首次登陆
        Member  member= memeberMapper.selectByOpenid(openid);
        // 如果用户信息不为空，说明老用户，生成token返回
        if(member != null){
         /*   Map<String ,Object>data=new HashMap<>();
            data.put("menberId",member.getId());
            data.put("name",member.getName());
            String token = JwtUtil.createJWT("itheima", 2, data);
            MemeberVo memeberVo = BeanUtil.copyProperties(member,MemeberVo.class);
            memeberVo.setToken(token);
            return  memeberVo;*/
            return buildMemeberVo(member);
        }
        // 如果用户信息为空，说明是新用户
        AccessTokenResultDto accessTokenResultDto = wxService.accessToken();
        if(accessTokenResultDto.getErrcode() != null){
            throw new BaseException( BasicEnum.WX_LOGIN_ERROR);
        }
        log.info("access token：{}", accessTokenResultDto.getAccess_token());
        // 调用wx的获取手机号的接口
        PhoneNumberResultDto phoneNumber   = wxService.getPhoneNumber(accessTokenResultDto.getAccess_token(),dto.getPhoneCode());
            if(Objects.equals(phoneNumber.getErrcpde(),0)){
                throw new BaseException( BasicEnum.WX_LOGIN_ERROR);
            }
        log.info("phone number：{}", phoneNumber.getPhone_info().getPurePhoneNumber());
        //
        Member insert = new Member();
        insert.setName(dto.getNickName());
        insert.setPhone(phoneNumber.getPhone_info().getPurePhoneNumber());
        insert.setOpenId(openid);
        insert.setGender(0);
        memeberMapper.insert(insert);
        return buildMemeberVo(insert);


    }

    public MemeberVo buildMemeberVo(Member member){
        Map<String, Object> data= new HashMap<>();
        data.put(jwtConstants.MEMBER_ID, member.getId());
        data.put(jwtConstants.MEMBER_NAME, member.getName());
        String token = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), data);
        MemeberVo memeberVo = BeanUtil.copyProperties(member, MemeberVo.class);
        memeberVo.setToken(token);
        memeberVo.setNickName(member.getName());
        return memeberVo;
    }
}

